import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import {
  CascaderItem,
  DialogService,
  DValidateRules,
  FileUploader,
  FormLayout,
  IFileOptions,
  IUploadOptions,
} from 'ng-devui';
import { PostEmploy, PutEmploy } from 'src/app/@core/data/employ';
import { RoleService } from 'src/app/@core/services/role/role.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectWorkShopComponent } from 'src/app/@shared/components/select-work-shop/select-work-shop.component';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-edit-employs',
  templateUrl: './edit-employs.component.html',
  styleUrls: ['./edit-employs.component.scss'],
})
export class EditEmploysComponent {
  layoutDirection: FormLayout = FormLayout.Horizontal;
  isManagerType = ['是', '否'];
  isDormitoryType = ['是', '否'];
  employTypes = ['本地员工', '外地员工'];
  isInsuredType = ['参保', '未参保'];
  genderType = ['男', '女'];
  isManager = '否';
  gender = '男';
  isInsured = '参保';
  employeeType = '本地员工';
  isDormitory = '否';
  departmentOptions: any = []; //部门
  roleOptions: any = []; //角色
  isDropOver: boolean = false;
  EntryDate = new Date();
  uploadedFiles: Array<Object> = [];
  departmentId: Array<number> = [];
  UserRoles: any = [];
  UPLOADED: string = '上传成功';
  CANCELUPLOAD: string = '取消上传';
  dispaly = false;
  fileUploaders: Array<FileUploader> = [];
  imgDisplay = false;
  msgs: Array<Object> = []; //消息提示
  uploadOptions: IUploadOptions = {
    uri: environment.apiUrl + '/User/UploadAvatar',
    maximumSize: 1024,
    checkSameName: true,
  };
  fileOptions: IFileOptions = {
    accept: '.png,.jpg,.jpeg,.gif,.bmp,.wbmp,.webp',
    multiple: true,
  };
  PostEmploy: PostEmploy = {
    employeeCode: '',
    name: '',
    jobNumber: '',
    departmentId: null,
    isManager: false,
    accountNumber: '',
    position: null,
    workshop: null,
    gender: false,
    entryDate: null,
    ownerPhoneNumber: null,
    ownerEmail: null,
    identityCardNumber: null,
    bankName: null,
    accountHolder: null,
    bankAccountNumber: null,
    address: null,
    employeeType: false,
    isInsured: null,
    contractStartDate: null,
    contractEndDate: null,
    resignationDate: null,
    salaryCategory: null,
    isDormitory: false,
    headImgUrl: null,
    enabled: true,
    userRoles: [],
    departmentName: '',
    departmentNum: '',
    password: '',
  };
  PostEmployRules: { [key: string]: DValidateRules } = {
    employeeCodeRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message: '不能包含空格',
        },
      ],
    },
    nameRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
      ],
    },
    jobNumberRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message: '不能包含空格',
        },
      ],
    },
    accountNumberRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message: '不能包含空格',
        },
      ],
    },
    passwordules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 6 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message: '不能包含空格',
        },
      ],
    },
    UserRolesRules: {
      messageShowType: 'text',
      validators: [
        { required: true },
        { minlength: 1 },
        { maxlength: 40 },
        {
          pattern: /^[^\s]*$/,
          message: '不能包含空格',
        },
      ],
    },
    departmentIdules: {
      messageShowType: 'text',
      validators: [{ required: true }],
    },
    telephoneRules: {
      messageShowType: 'text',
      validators: [{ minlength: 1 }, { maxlength: 11 }, { whitespace: true }],
    },
    emailRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 40 },
        { whitespace: true },
        {
          pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
          message: '请输入正确的邮箱，例如:example@example.com',
        },
      ],
    },
    cardNumberRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 18 },
        { whitespace: true },
        {
          pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: '请输入正确的身份证号码',
        },
      ],
    },
    bankAccountNumberRules: {
      messageShowType: 'text',
      validators: [
        { minlength: 1 },
        { maxlength: 19 },
        { whitespace: true },
        {
          pattern: /^\d+$/,
          message: '请输入正确的银行账号',
        },
      ],
    },
  };
  headerURL: any;
  constructor(
    private UserService: UserService,
    private roleService: RoleService,
    private route: ActivatedRoute,
    private Router: Router,
    private dialogService: DialogService
  ) {}
  ngOnInit(): void {
    this.imgDisplay = true;
    this.PostEmploy.isManager = this.isManager == '是' ? true : false;
    this.PostEmploy.gender = this.gender == '男' ? true : false;
    this.PostEmploy.employeeType =
      this.employeeType == '本地员工' ? true : false;
    this.route.params.subscribe((params) => {
      this.PostEmploy.employeeCode = params['id'];
      this.UserService.GetUserByEmployeeCode(
        this.PostEmploy.employeeCode
      ).subscribe((data: PutEmploy) => {
        this.PostEmploy = data;
        this.gender = data.gender ? '男' : '女';
        this.isManager = data.isManager ? '是' : '否';
        this.employeeType = data.employeeType ? '本地员工' : '外地员工';
        this.isDormitory = data.isDormitory ? '是' : '否';
        this.isInsured = data.isInsured ? '参保' : '未参保';
        this.EntryDate = new Date(data.entryDate);
        this.PostEmploy.contractStartDate = new Date(data.contractStartDate);
        this.PostEmploy.contractEndDate = new Date(data.contractEndDate);
        this.PostEmploy.resignationDate = new Date(data.resignationDate);
        this.headerURL =
          environment.modifiedApiUrl + this.PostEmploy.headImgUrl;
        this.UserService.GetAllDepartments(1, 999).subscribe((data: any) => {
          this.departmentOptions = this.convertToCascaderItem(
            data.items,
            'departmentId'
          );
          let department = this.findDepartmentByValue(
            this.departmentOptions,
            this.PostEmploy.departmentId
          );
          this.departmentId = department ? department : [];
          this.roleService.getAllRoles(1, 999).subscribe((data: any) => {
            this.roleOptions = data.items
              .filter((item: { name: any }) => item.name !== '超级管理员')
              .map((item: { name: any }) => item.name);
          });
        });
      });
    });
  }
  dropdownToggle($event: any) {}
  convertToCascaderItem(data: any[], valueKey: any): CascaderItem[] {
    return data.map((item) => {
      let cascaderItem: CascaderItem = {
        label: item.name,
        value: item[valueKey],
        icon: item.icon,
        name: item.departmentCode,
        disabled: item.disabled,
      };
      if (item.subDepartments) {
        cascaderItem.children = this.convertToCascaderItem(
          item.subDepartments,
          valueKey
        );
      }
      return cascaderItem;
    });
  } //转换数据格式为华为库练级菜单的数据格式
  submit(valid: any) {
    this.dispaly = true;
    if (this.departmentId.length > 0) {
      this.PostEmploy.departmentId =
        this.departmentId[this.departmentId.length - 1];
    }
    this.PostEmploy.isManager = this.isManager == '是' ? true : false;
    this.PostEmploy.gender = this.gender == '男' ? true : false;
    this.PostEmploy.employeeType =
      this.employeeType == '本地员工' ? true : false;
    this.PostEmploy.isDormitory = this.isDormitory == '是' ? true : false;
    this.PostEmploy.isInsured = this.isInsured == '参保' ? true : false;
    this.PostEmploy.entryDate = this.EntryDate.toISOString().slice(0, 10);
    let postEmployNonNull = Object.entries(this.PostEmploy).reduce(
      (newObj, [key, value]) => {
        if (value !== null) {
          newObj[key] = value;
        }
        return newObj;
      },
      {}
    );
    if (valid.valid) {
      this.UserService.UpdateUser(
        postEmployNonNull,
        this.PostEmploy.employeeCode
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '人员更新成功！');
          let userinfo = localStorage.getItem('userinfo');
          if (!userinfo) {
            userinfo = sessionStorage.getItem('userinfo');
          }
          let user = userinfo ? JSON.parse(userinfo) : null;
          if (user && user.accountNumber == this.PostEmploy.accountNumber) {
            user.headUrl = this.PostEmploy.headImgUrl;
            user.username = this.PostEmploy.name;
            // user.roles = this.PostEmploy.userRoles;
            localStorage.setItem('userinfo', JSON.stringify(user));
          }
          setTimeout(() => {
            this.Router.navigate(['/pages/basicdata/employs']);
          }, 1000);
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error);
          }
        }
      );
    } else {
      this.showToast('warn', '警告', '请按照要求填写表单！');
    }
  }
  onFileSelected(event: any) {
    const file: File = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => {
        localStorage.setItem('avatar', reader.result.toString());
      };
      reader.readAsDataURL(file);
    }
  }
  onSuccess(event: any) {
    let response = JSON.parse(event[0].response);
    let avatarUrl = response.avatarUrl;
    let baseUrl = environment.modifiedApiUrl;
    this.PostEmploy.headImgUrl = avatarUrl.replace(baseUrl, '');
    this.headerURL = avatarUrl;
  } //上传成功
  onError(event: any) {} //上传失败
  fileDrop(files: File) {
    this.isDropOver = false;
  } //拖拽文件
  fileOver(event: any) {
    this.isDropOver = event;
  } //拖拽文件
  fileSelect(files: any) {} //文件选择
  deleteimg() {
    this.imgDisplay = false;
  }
  deleteFile(currFile: FileUploader) {
    this.fileUploaders = this.fileUploaders.filter((fileUploader) => {
      return currFile !== fileUploader;
    });
  } //删除文件

  cancel() {
    this.Router.navigate(['/pages/basicdata/employs']);
  }
  findDepartmentByValue(
    arr: any[],
    value: any,
    path: any[] = []
  ): any[] | null {
    for (let i = 0; i < arr.length; i++) {
      const currentPath = [...path, arr[i].value];
      if (arr[i].value === value) {
        return currentPath;
      } else if (Array.isArray(arr[i].children) && arr[i].children.length > 0) {
        const result = this.findDepartmentByValue(
          arr[i].children,
          value,
          currentPath
        );
        if (result) {
          return result;
        }
      }
    }
    return null;
  }

  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  findDepartmentById(departments: any[], departmentId: number): any {
    for (const dept of departments) {
      if (dept.value === departmentId) {
        return dept;
      }
      if (dept.children && dept.children.length > 0) {
        const found = this.findDepartmentById(dept.children, departmentId);
        if (found) {
          return found;
        }
      }
    }
    return null;
  }
  cascaderonChanges($event: any) {
    this.dispaly = true;
    const selectedDepartmentId = $event[$event.length - 1];
    const selectedDepartment = this.findDepartmentById(
      this.departmentOptions,
      selectedDepartmentId
    );
    if (selectedDepartment) {
      this.PostEmploy.departmentName = selectedDepartment.label;
      this.PostEmploy.departmentNum = selectedDepartment.name;
    } else {
      // 处理未找到相应部门的情况
      console.error('未找到相应的部门信息');
    }
  }
  selectWorkShop(DialogService?: string) {
    let data = {
      display: false,
      placeholder: '请选择车间',
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '800px',
      title: '车间',
      data: data,
      content: SelectWorkShopComponent,
      dialogtype: DialogService,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              this.PostEmploy.workshop =
                results.modalContentInstance.selectData.workshopName;
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
